require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"


class IndividualAccuracy
  
  NAME = "Normalized Individual Accuracy (Adjusted Backspace counts for each phrase)"
    
  
    def analyze(directory, experimentalData, phraseCards)
      
      #create the report
      report = Report.new(directory, NAME)
      
      #get the data by uid    
      data = experimentalData.group_by_uid
          
      data.each_pair do |uid, entries|
        data_by_layer = {}
        
        entries.each do |e|
          #initialize if nil
          data_by_layer[e.layer] ||= []
          data_by_layer[e.layer] << e
        end
        
        #create a graph for each uid
        g = create_graph(uid)
        
        #do some simple statistics
        stat = ""
        
        #Generate a section for each tech layer
        data_by_layer.each_pair do |layer, entries|
           entries.sort! { |x,y| x.date <=> y.date }  
             
           accuracies = entries.collect do |e|
             _count_backspace(e).to_f / phraseCards.getPhrase(e.set, e.phrase).length
           end   
           
           avg = accuracies.inject{ |sum, el| sum + el }.to_f / accuracies.length  
           
           g.data "Layer:#{layer}", accuracies
           stat = stat + "<b>Layer #{layer}:</b> " +  
                  "finished(phrases):#{entries.length} " +
                  "average error rate: #{avg}" +
                  "<br/>" 
        end
        
        report.new_section("Subject #{uid}", stat, g)  
          
      end
  
      #generate report  
      report.to_html
    end
    
    def create_graph (uid)
      g = Gruff::Line.new
      g.dot_radius = 2
      g.line_width = 2
      g.x_axis_label = "Phrases"
      g.y_axis_label = "Error"
      g.title = "Individual Error Rate (UID:#{uid})"
      g
    end
    
    def _count_backspace(e)
      #count the number of backspace
      counter = 0
      state = :normal
      e.sequence.each do |seq|
        if ( seq[0].eql?("\b"))
          counter = counter + 1 if state == :normal
          state = :consecutive_bs
        else
          state = :normal
        end
      end
      counter
    end
end